package com.uzykj.mall.config;

import com.uzykj.mall.util.qiniu.QiniuUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤器
 * @date  2018-10-28 晚上20：07
 * @author gostxbh
 */
public class ServletFilterConfig implements Filter{

	private static final Logger logger = LogManager.getLogger(ServletFilterConfig.class);
	private static final String FILTERED_REQUEST = "@@session_context_filtered_request";
	private static final String[] INHERENT_ESCAPE_URIS = {"/","error", "logout","getsign", "index" , "admin/login/doLogin"};

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		if (isURILogin(req.getRequestURI())){
			logger.info("不用校验登录");
			filterChain.doFilter(request, response);
		}else {
			logger.info("校验登录");
			String adminId = req.getSession().getAttribute("adminId").toString();
			if (StringUtils.isEmpty(adminId)) {
				res.sendRedirect("/login");
				return ;
			}else {
				filterChain.doFilter(request, response);
			}
		}
	}

	@Override
	public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {
		QiniuUtil.getInstance();
	}

	
	private boolean isURILogin(String requestURI) {
		for (String uri : INHERENT_ESCAPE_URIS) {
			if (requestURI != null && requestURI.indexOf(uri) >= 0) {
				return true;
			}
		}
		return false;
	}
}
